package com.tanger.im;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.ServiceException;
import com.fasterxml.jackson.databind.JsonNode;
import com.tanger.common.files.FilesConfig;
import com.tanger.common.files.FilesObject;
import com.tanger.common.utils.MD5Util;
import com.tanger.common.utils.WebClientUtil;
import com.tanger.im.entity.IMQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Objects;

/**
 * @Description 生成JSON文件并上传工具
 * @Author Hchenbin
 * @Date 2023/12/25 18:36
 * @Version 1.0
 */
@Slf4j
public class IMUserRecordHelper {

    private static final String CHARSET_NAME = "UTF-8";
    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMdd");

    /**
     * 生成JSON文件
     * @param datas 数据
     * @param groupId 分组ID
     * @param fId 接收人ID
     * @param tId 发送人ID
     */
    public static void save(Object datas, String groupId, String fId, String tId) {
        String filename = fileName(groupId, fId, tId);
        try {
            save(datas, filename);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 生成JSON文件
     * @param datas 数据
     * @param fileName 文件名
     */
    public static void save(Object datas, String fileName) {
        // 初始化流
        InputStream inputStream = null;
        String PLUGIN_BUCKET_PATH ="";
        Writer out = null;
        try {
            PLUGIN_BUCKET_PATH = ResourceUtils.getURL("classpath:").getPath().replace("WEB-INF/classes/","");

            genrate(PLUGIN_BUCKET_PATH,FilesConfig.imDir,fileName+".json");
            String url_1 = PLUGIN_BUCKET_PATH + FilesConfig.imDir +fileName+".json";
            File file = new File(url_1);
            //输入流,进行写入操作
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "utf-8"), 10240);

            //查询建筑下所有VR点
            out.write(JSON.toJSONString(datas));
            //清空缓存区,完全写入
            out.flush();
            //关闭流
            out.close();
            inputStream = new FileInputStream(url_1);
            if (FilesConfig.type.equalsIgnoreCase("LOCAL")){
                new FilesObject().putObject(inputStream,PLUGIN_BUCKET_PATH,FilesConfig.imDir,fileName+".json");
            }else {
                final String key = FilesConfig.imDir + fileName+".json";
                new FilesObject().putObject(inputStream,key);
            }
        } catch (IOException e) {
            throw new ServiceException(e.getMessage());
        }finally {
            try {
                inputStream.close();
                if (!FilesConfig.type.equalsIgnoreCase("LOCAL")) {
                    delete(PLUGIN_BUCKET_PATH,FilesConfig.imDir,fileName+".json");
                }
            }catch (IOException e){
                throw new ServiceException(e.getMessage());
            }
        }
    }

    public static boolean delete(String... key){
        //校验目录
        int len = key.length, i = 0;
        //定义最终的目录
        String fileDirPath = key[0];
        for (String k : key) {
            //从索引1开始至倒数第一个
            if (i == 0 || i >= len - 1) {
                i++;
                continue;
            }
            File file = new File(fileDirPath, k);
            if (!file.exists()) return false;
            fileDirPath = file.toString();
            i++;
        }
        if (StringUtils.isEmpty(fileDirPath)) return false;
        File targetFile = new File(fileDirPath, key[len - 1]);
        if (!targetFile.exists()) return false;
        return targetFile.delete();
    }

    public static boolean genrate(String... key){
        //创建目录（key的结构为   {"/usr/local/src/", "map", "00230021", "123456.png"}）
        int len = key.length, i = 0;
        //定义最终的目录
        String fileDirPath = key[0];
        for (String k : key) {
            //从索引1开始至倒数第一个
            if (i == 0 || i >= len - 1) {
                i++;
                continue;
            }
            File file = new File(fileDirPath, k);
            if (!file.exists()) file.mkdirs();
            fileDirPath = file.toString();
            i++;
        }
        if (StringUtils.isEmpty(fileDirPath)) return false;
        try {
            File targetFile = new File(fileDirPath, key[len - 1]);
            if (targetFile.exists())  targetFile.delete();
            targetFile.createNewFile();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     *
     * @param groupId 分组ID
     * @param fId 接收人ID
     * @param tId 发送人ID
     * @return
     */
    private static String fileName(String groupId, String fId, String tId) {
        String pu = "";
        if (Objects.isNull(groupId)) {
            pu = MD5Util.encode(fId + tId);
        } else {
            pu = MD5Util.encode(groupId);
        }
        return pu;
    }

    /**
     * 读取JSON文件
     * @param query 查询条件
     */
    public static JsonNode read(IMQuery query) {
        return read(fileName(inint(query.getGroupId()), inint(query.getFuId()), inint(query.getTuId())));
    }

    /**
     * 读取JSON文件
     * @param fileName 查询条件
     */
    public static JsonNode read(String fileName) {
        String PLUGIN_BUCKET_PATH ="";
        try {
            PLUGIN_BUCKET_PATH = ResourceUtils.getURL("classpath:").getPath().replace("WEB-INF/classes/","");

            String url = PLUGIN_BUCKET_PATH + FilesConfig.imDir +fileName+".json";
            if (FilesConfig.type.equalsIgnoreCase("LOCAL")){
                return readLocal(url);
            }
            return WebClientUtil.get(url);
        } catch (IOException e) {
            throw new ServiceException(e.getMessage());
        }
    }

    private static JsonNode readLocal(String url) {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(url), CHARSET_NAME))) {
            StringBuffer sb = new StringBuffer();
            String str;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            return com.tanger.common.utils.JSON.parse(sb.toString(),JsonNode.class);
        } catch (Exception e) {
            log.info("读取聊天记录异常: {}",e.getMessage());
            return null;
        }
    }

    private static String inint(Long varl) {
        if (Objects.isNull(varl)) {
            return null;
        }
        return varl.toString();
    }
}
